package com.lx.chong.controller;

import com.alibaba.fastjson.JSONObject;
import com.lx.chong.common.Result;
import com.lx.chong.dto.UserDto;
import com.lx.chong.enums.ResultEnum;
import com.lx.chong.form.UserForm;
import com.lx.chong.model.User;
import com.lx.chong.service.impl.UserServiceImpl;
import com.lx.chong.utils.MD5Util;
import com.lx.chong.utils.RandomValidateCodeUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

/**
 * @author: chong
 * @date: 2018/8/23
 */
@Slf4j
@Api(description = "用户信息API")
@RestController
public class UserController {

    @Autowired
    UserServiceImpl userService;

    @Value("sessionKey")
    private String sessionKey;

    @Autowired
    private StringRedisTemplate redisTemplate;
/*

    @Resource
    private RedisTemplate<String,Object> objectRedisTemplate;
*/

    /**
     * 获取用户列表
     *
     * @param dto
     * @return
     */
    @ApiOperation(value = "获取用户列表")
    @ApiImplicitParams({@ApiImplicitParam(name = "start", value = "开始页", dataType = "Integer"),
            @ApiImplicitParam(name = "total", value = "每页显示个数", dataType = "Integer")})
    @PostMapping("/getUserListPage")
    public Result getUserListPage(@RequestBody UserDto dto) {
        Result result = new Result();
        try {
            List<User> userListPage = userService.getUserListPage(dto.getPage(), dto.getSize());
            Long totalPage = userService.getTotalPage();
            Page<User> page = new PageImpl(userListPage, null, totalPage);
            result.setData(page);
        } catch (Exception e) {
            result.setCode(ResultEnum.OPERATION_ERROR.getCode());
            log.error(e.getMessage());
        }
        return result;
    }

    @ApiOperation(value = "获取用户列表_传参")
    @PostMapping("/getUserListPages")
    public Result getUserListPages(@RequestBody UserDto dto) {
        Result result = new Result();
        try {
            List<User> userListPage = userService.queryUserList(dto);
            Long totalPage = userService.getTotalPage(dto);
            Page<User> page = new PageImpl(userListPage, null, totalPage);
            result.setData(page);
        } catch (Exception e) {
            result.setCode(ResultEnum.OPERATION_ERROR.getCode());
            log.error(e.getMessage());
        }
        return result;
    }

    /**
     * 保存用户信息
     *
     * @param userForm
     * @return
     */
    @ApiOperation(value = "保存用户信息")
    @PutMapping("/saveUser")
    public Result saveUser(@RequestBody UserForm userForm) {
        Result result = new Result();
        User user = new User();
        try {
            BeanUtils.copyProperties(userForm, user);
            if (user.getId() == null) {
                user.setAddDateTime(new Date());
//                user.setUseMark(0); // 禁用
                user.setApproveStatus(0); // 待审核
                // 初始化密码为123456
                user.setPassword(MD5Util.getMD5String("123456"));
            } else {
                User one = userService.findOne(user.getId());
                user.setAddDateTime(one.getAddDateTime());
            }
            User save = userService.save(user);
            result.setData(save);
        } catch (Exception e) {
            result.setCode(ResultEnum.OPERATION_ERROR.getCode());
            result.setMsg("保存用户信息异常");
            log.error(e.getMessage());
        }
        return result;
    }

    /**
     * 根据id获取对象
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "根据id获取对象")
    @PostMapping("/getUserById")
    public Result getUserById(@RequestBody Long id) {
        Result result = new Result();
        try {
            User user = userService.findOne(id);
            result.setData(user);
        } catch (Exception e) {
            result.setCode(ResultEnum.OPERATION_ERROR.getCode());
            result.setMsg("根据id获取对象异常");
            log.error(e.getMessage());
        }
        return result;
    }

    /**
     * 删除用户
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "删除用户")
    @PostMapping("/deleteUser")
    public Result deleteUser(@RequestBody Long id) {
        Result result = new Result();
        try {
            User user = userService.findOne(id);
            user.setIfDelete(1);
            User save = userService.save(user);
            result.setData(save);
        } catch (Exception e) {
            result.setCode(ResultEnum.OPERATION_ERROR.getCode());
            result.setMsg("删除用户");
            log.error(e.getMessage());
        }
        return result;
    }

    @PostMapping("/getUserBySid")
    public Result getUserBySid(@RequestBody JSONObject json) {
        Result result = new Result();
        try {
            Long id = json.getLong("id");
            User user = userService.findOne(id);
            result.setData(user);
        } catch (Exception e) {
            result.setCode(ResultEnum.OPERATION_ERROR.getCode());
            result.setMsg("根据id获取对象异常");
            log.error(e.getMessage());
        }
        return result;
    }
    /**
     * 删除用户  对象接受参数
     * @param obj
     * @return
     */
    @PostMapping("/delUser")
    public Result delUser(@RequestBody JSONObject obj) {
        Result result = new Result();
        try {
            Long id = obj.getLong("id");
            User user = userService.findOne(id);
            user.setIfDelete(1);
            User save = userService.save(user);
            result.setData(save);
        } catch (Exception e) {
            result.setCode(ResultEnum.OPERATION_ERROR.getCode());
            result.setMsg("删除用户");
            log.error(e.getMessage());
        }
        return result;
    }

    /**
     * 启用禁用
     *
     * @param object
     * @return
     */
    @ApiOperation(value = "启用禁用")
    @PostMapping("/changeUserMark")
    public Result changeUserMark(@RequestBody JSONObject object) {
        Result result = new Result();
        try {
            Long id = object.getLong("id");
            Integer status = object.getInteger("status");
            User one = userService.findOne(id);
            one.setUseMark(status == 1 ? 0 : 1);
            User save = userService.save(one);
            result.setData(save);
        } catch (Exception e) {
            result.setCode(ResultEnum.OPERATION_ERROR.getCode());
            result.setMsg("启用禁用");
            log.error(e.getMessage());
        }
        return result;
    }

    /**
     * 生成验证码
     */
    @RequestMapping(value = "/getVerify")
    public void getVerify(HttpServletRequest request, HttpServletResponse response) {
        try {
            response.setContentType("image/jpeg");//设置相应类型,告诉浏览器输出的内容为图片
            response.setHeader("Pragma", "No-cache");//设置响应头信息，告诉浏览器不要缓存此内容
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expire", 0);
            RandomValidateCodeUtil randomValidateCode = new RandomValidateCodeUtil();
            randomValidateCode.getRandcode(request, response);//输出验证码图片方法
        } catch (Exception e) {
            log.error("获取验证码失败>>>> ", e);
        }
    }

    /**
     * 登录
     * @param object
     * @return
     */
    @ApiOperation(value = "登录")
    @PostMapping("/login")
    public Result login(@RequestBody JSONObject object) {
        Result result = new Result();
        try {
            String account = object.getString("account");
            String pwd = object.getString("pwd");
            String code = object.getString("code");
            String redisCode = redisTemplate.opsForValue().get(sessionKey);
            if (code.equalsIgnoreCase(redisCode)) {
                User user = userService.queryUserByAccountOrMobile(account);
                if (user == null) {
                    result.setCode(ResultEnum.OPERATION_ERROR.getCode());
                    result.setMsg("用户不存在");
                    return result;
                } else {
                    if (!user.getPassword().equals(MD5Util.getMD5String(pwd))) {
                        result.setCode(ResultEnum.OPERATION_ERROR.getCode());
                        result.setMsg("密码错误");
                        return result;
                    }else {
                        result.setData(user);
//                        objectRedisTemplate.opsForValue().set("userInfo",user);
                    }
                }
            } else {
                result.setCode(ResultEnum.OPERATION_ERROR.getCode());
                result.setMsg("编号有误");
                return result;
            }
        } catch (Exception e) {
            result.setCode(ResultEnum.OPERATION_ERROR.getCode());
            result.setMsg("登录异常");
            log.error(e.getMessage());
        }
        return result;
    }
    /**
     * 查询未删除的用户
     * @return
     */
    @GetMapping("/findAllByIfDelete")
    public Result findAllByIfDelete() {
        Result result = new Result();
        try {
            List<User> allByIfDelete = userService.findAllByIfDelete();
            result.setData(allByIfDelete);
        } catch (Exception e) {
            result.setCode(ResultEnum.OPERATION_ERROR.getCode());
            result.setMsg("查询未删除的用户");
            log.error(e.getMessage());
        }
        return result;
    }
}
